import { useEffect, useState, KeyboardEvent, MouseEvent, useCallback } from "react";
import { Form } from 'antd';

import { globalStore, prompt } from "@/service";
import { RespDataType, login, getCaptchaImage, getUserInfo } from "../api";


export const useAccountLogin = () => {
  const [submitting, setSubmitting] = useState(false);
  const [captchaImageInfo, setCaptchaImageInfo] = useState<RespDataType.ICaptchaImageInfo>({
    img: "",
    uuid: ""
  });
  const [form] = Form.useForm();

  useEffect(() => {
    fetchCaptchaImage();
  }, []);

  // 获取验证码图片
  const fetchCaptchaImage = useCallback(() => {
    getCaptchaImage().then((resp) => {
      resp.data.img = "data:image/png;base64," + resp.data.img
      setCaptchaImageInfo(resp.data);
    })
  }, [])

  const handleSubmit = (e?: KeyboardEvent<HTMLInputElement> | MouseEvent<HTMLElement>) => {
    e = e as KeyboardEvent<HTMLInputElement>;
    if (e.type == "click" || (e.code && e.code.toLocaleLowerCase() == "enter")) {
      setSubmitting(true);
      form.validateFields().then((resp) => {
        const { loginName, password, code } = resp;
        login({ username: loginName, password, code: code, uuid: captchaImageInfo.uuid }).then((_resp) => {
          getUserInfo().then(() => {
            // 1. 保存请求token
            prompt.success("登录成功!");
            setSubmitting(false);
            globalStore.closeLoginModal();

            setTimeout(() => {
              window.location.reload()
            }, 1000)
          }).catch(() => setSubmitting(false))
          // window.location.href = EnumRouter.appRoot;
         
        }).catch(() => {
          fetchCaptchaImage();
          setSubmitting(false);
        });

      }).catch(() => {
        setSubmitting(false)
      })
    }
  }

  return { submitting, handleSubmit, form, captchaImageInfo, fetchCaptchaImage }
}
